﻿using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL;
using Models;

namespace UI
{
    public partial class Index : Form
    {
        private BooksBLL booksBLL;
        private DataPage page;
        private bool state = false;
        public Index()
        {
            InitializeComponent();
            booksBLL = new BooksBLL();
            Init();
            LoadTable();
        }
        public void Init()
        {
            PageSize.SelectedIndex = 0;
            GetDataPage();
        }
        public DataPage GetDataPage()
        {
            return page = new DataPage()
            {
                PageSize = Convert.ToInt32(PageSize.SelectedItem),
                PageIndex = Convert.ToInt32(PageIndex.Text)
            };
        }
        public void LoadTable(string name = "", string url = "")
        {
            BookListView.Items.Clear();
            var list = booksBLL.QueryBooks(ref page, name, url);

            foreach (var book in list)
            {
                ListViewItem lv = new ListViewItem();
                lv.Text = book.Name;
                lv.SubItems.Add(book.Href);
                lv.SubItems.Add(book.State);
                lv.SubItems.Add(book.AddTime.ToString("yyyy-MM-dd HH:mm:ss"));
                BookListView.Items.Add(lv);
            }

            PageCount.Text = page.PageCount.ToString();
        }

        #region 分页事件
        private void PageFirst_Click(object sender, System.EventArgs e)
        {
            PageIndex.Text = "1";
            GetDataPage();
            LoadTable();
        }

        private void PageUp_Click(object sender, System.EventArgs e)
        {
            if (page.PageIndex > 1)
            {
                PageIndex.Text = (page.PageIndex - 1).ToString();
                GetDataPage();
                LoadTable();
            }
        }

        private void PageSize_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            GetDataPage();
            LoadTable();
        }

        private void PageIndex_TextChanged(object sender, System.EventArgs e)
        {
            if (int.TryParse(PageIndex.Text, out int pi))
            {
                GetDataPage();
                LoadTable();
            }
            else
            {
                PageIndex.Text = page.PageIndex.ToString();
                MessageBox.Show("请输入正确的页码");
            }
        }

        private void PageDown_Click(object sender, System.EventArgs e)
        {
            if (page.PageIndex < page.PageCount)
            {
                PageIndex.Text = (page.PageIndex + 1).ToString();
                GetDataPage();
                LoadTable();
            }
        }

        private void PageLast_Click(object sender, System.EventArgs e)
        {
            PageIndex.Text = page.PageCount.ToString();
            GetDataPage();
            LoadTable();
        }
        #endregion
        #region 菜单事件
        private void TaskSetting_Click(object sender, EventArgs e)
        {
            new TaskPanel().Show();
        }
        private void Search_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Search.Text == "按下Enter时搜索")
            {
                Search.ForeColor = Color.Black;
                Search.Text = "";
                return;
            }
            if (e.KeyChar == 13)
            {
                LoadTable(Search.Text);
            }
        }
        #endregion

        private void DownloadBookList_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    booksBLL.GetBooksFromHttp(Properties.Settings.Default.BooksURL);
                }));
            });
            task.Start();

        }

        private void DownloadChapters_Click(object sender, EventArgs e)
        {
            var count = booksBLL.QueryProgress();
            DownloadChapterProgress.Minimum = 0;
            DownloadChapterProgress.Maximum = count[1];
            DownloadChapterProgress.Value  = count[0];

            DownloadChapterWork.WorkerSupportsCancellation = true;
            DownloadChapterWork.RunWorkerAsync();
        }
        private void DownloadContent_Click(object sender, EventArgs e)
        {

        }

        private void StopTask_Click(object sender, EventArgs e)
        {
            DownloadChapterWork.CancelAsync();
        }
        private delegate void DelegateUpdateProgress();
        private void DownloadChapterWork_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    var book = booksBLL.QueryBook();
                    DelegateUpdateProgress dup1 = delegate {
                        this.Books.Text = $"正在下载《{book.Name}》的章节";
                    };
                    this.Books.Invoke(dup1);
                    if (book != null)
                    {
                        var result = booksBLL.GetChapterList(book);
                        if (result)
                        {

                            DelegateUpdateProgress dup2 = delegate {
                                DownloadChapterProgress.Value++;
                            };
                            this.DownloadChapterProgress.Invoke(dup2);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    DelegateUpdateProgress dup3 = delegate {
                        this.Books.Text = $"下载出错:"+ ex.Message;
                    };
                    this.Books.Invoke(dup3);
                }
            }
            DelegateUpdateProgress dup4 = delegate {
                this.Books.Text = $"下载完毕";
            };
            this.Books.Invoke(dup4);
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            LoadTable();
        }
    }
}
